import sqlite3

print("=== 修正n8n用户映射 ===")

# 连接到数据库
conn = sqlite3.connect('./openmemory.db')
cursor = conn.cursor()

# 1. 检查当前用户状态
cursor.execute("SELECT id, name FROM users")
users = cursor.fetchall()
print("当前用户:")
for user in users:
    print(f"   - ID: {user[0]}, 名称: '{user[1]}'")

# 2. 找到"Default User"并改名为"default_user"
cursor.execute("SELECT id FROM users WHERE name = 'Default User'")
default_user = cursor.fetchone()

if default_user:
    user_id = default_user[0]
    print(f"\n找到Default User (ID: {user_id})")
    
    # 更新用户名为"default_user"
    cursor.execute("UPDATE users SET name = 'default_user' WHERE id = ?", (user_id,))
    conn.commit()
    print("✅ 已将 'Default User' 重命名为 'default_user'")
    
    # 3. 验证更新后的记忆
    cursor.execute("""
        SELECT u.name, a.name, COUNT(m.id) as memory_count
        FROM users u
        JOIN memories m ON u.id = m.user_id
        JOIN apps a ON m.app_id = a.id
        WHERE u.name = 'default_user'
        GROUP BY u.id, u.name, a.id, a.name
    """)
    
    memories = cursor.fetchall()
    print(f"\n修正后default_user的记忆:")
    for user_name, app_name, count in memories:
        print(f"   - {user_name} -> {app_name}: {count} 条记忆")

else:
    # 检查是否有其他用户需要修正
    cursor.execute("SELECT id FROM users WHERE name = 'None'")
    none_user = cursor.fetchone()
    
    if none_user:
        print(f"\n找到None用户 (ID: {none_user[0]})")
        # 将None用户的记忆转移到default_user
        cursor.execute("UPDATE users SET name = 'default_user' WHERE id = ?", (none_user[0],))
        conn.commit()
        print("✅ 已将 'None' 重命名为 'default_user'")

# 4. 检查最终状态
cursor.execute("SELECT id, name FROM users")
final_users = cursor.fetchall()
print(f"\n最终用户状态:")
for user in final_users:
    print(f"   - ID: {user[0]}, 名称: '{user[1]}'")

conn.close()

print("\n=== 修正完成 ===")
print("n8n工作流现在应该能找到记忆了！")